import {Component, OnInit} from '@angular/core';
import {Select, Store} from "@ngxs/store";
import {Observable} from "rxjs";
import {CartModel} from "../../../store/cart/cart.state";
import {Shop} from "../../../store/shop/shop.actions";
import {Cart} from "../../../store/cart/cart.actions";
import {RouterSelectors} from "../../../store/router/router";

@Component({
  selector: 'app-list',
  templateUrl: './list.component.html',
  styleUrls: ['./list.component.scss'],
})
export class ListComponent implements OnInit {

  @Select() cart$: Observable<CartModel>
  carts: Shop[] = []
  price = 0

  constructor(
    private store: Store,
  ) {
  }


  ngOnInit(): void {
    const q = this.store.selectSnapshot(RouterSelectors.queryParams)
    console.log('q', q)
    this.cart$.subscribe(r => {
      this.carts = r.list
    })
  }

  removeFromCart(item: Shop) {
    this.store.dispatch(new Cart.Remove(item.id))
  }

  pay() {
    const list = this.store.selectSnapshot<Shop[]>(s => s.cart.list)
    let price = 0
    for (let shop of list) {
      price += shop.price
    }
    this.price = price
  }
}
